#!/bin/bash

# 测试多端口配置脚本
echo "🧪 测试Ubuntu多端口配置..."

# 检查必要的文件
echo "📁 检查文件存在性："
files=("gensyn.sh" "run_rl_swarm_ubuntu.sh" "rgym_exp/config/rg-swarm.yaml")
for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        echo "✅ $file 存在"
    else
        echo "❌ $file 不存在"
    fi
done

# 检查端口配置
echo ""
echo "🔧 检查端口配置："
if grep -q "RL_SWARM_PORTS" ~/.zshrc 2>/dev/null; then
    echo "✅ 发现已有端口配置："
    grep "RL_SWARM_PORTS" ~/.zshrc
else
    echo "ℹ️ 未找到端口配置，首次运行时将提示配置"
fi

# 检查可执行权限
echo ""
echo "🔐 检查文件权限："
scripts=("gensyn.sh" "run_rl_swarm_ubuntu.sh")
for script in "${scripts[@]}"; do
    if [ -x "$script" ]; then
        echo "✅ $script 有执行权限"
    else
        echo "⚠️ $script 无执行权限，正在添加..."
        chmod +x "$script" 2>/dev/null || echo "❌ 无法添加执行权限到 $script"
    fi
done

# 检查端口占用
echo ""
echo "🌐 检查常用端口占用："
ports=(3000 3001 8000 8001)
for port in "${ports[@]}"; do
    if command -v lsof >/dev/null 2>&1; then
        if lsof -i :$port >/dev/null 2>&1; then
            echo "⚠️ 端口 $port 已被占用"
        else
            echo "✅ 端口 $port 可用"
        fi
    else
        echo "ℹ️ lsof 命令不可用，无法检查端口 $port"
    fi
done

# 检查系统依赖
echo ""
echo "📦 检查系统依赖："
deps=("python3" "node" "yarn")
for dep in "${deps[@]}"; do
    if command -v $dep >/dev/null 2>&1; then
        version=$($dep --version 2>/dev/null | head -n1)
        echo "✅ $dep: $version"
    else
        echo "❌ $dep 未安装"
    fi
done

echo ""
echo "🎯 测试完成！"
echo "💡 提示："
echo "   - 运行 './gensyn.sh' 开始配置"
echo "   - 多实例部署请参考 UBUNTU_MULTI_PORT_GUIDE.md"
echo "   - 如遇问题请检查日志文件 logs/yarn.log"